<template>
    <div class="right4">
        <div class="section">
            <div class="section__title">响应时长</div>
            <div class="chart-box">
                <div class="chart" ref="chartDom"></div>
            </div>

        </div>
        <div class="section">
            <div class="section__title">各保司推送线索量占比</div>
            <div class="table-box">
                <div class="table-wrapper">
                    <div class="table-body-scroll" ref="scrollContainer">
                        <table class="table unified-table" :class="{ scroll: extendedClue.length > 5 }">
                            <colgroup>
                                <col />           
                                <col width="50%"/> 
                                <col width="15%"/>  
                            </colgroup>
                            <tbody ref="scrollContent">
                                <tr v-for="(item, index) in extendedClue" :key="index">
                                    <td>{{ item.clue }}</td>
                                    <td>
                                        <div class="bar-wrapper">
                                            <div class="bar" :style="barStyle(item.percentageBar,['#2d79f3','#68d13f'])"></div>
                                        </div>
                                    </td>
                                    <td>{{ item.percentage }}%</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>    
        </div>
        <div class="section">
            <div class="section__title">战败原因</div>
            <div class="table-box">
                <div class="table-wrapper">
                    <div class="table-body-scroll" ref="scrollContainer2" >
                        <table class="table unified-table" :class="{ scroll: extendedReason.length > 5 }">
                            <colgroup>
                                <col />            <!-- 品牌（自适应） -->
                                <col width="50%"/>       <!-- 百分比 -->
                                <col width="15%"/>   <!-- 数量 -->
                                <col width="15%"/>  <!-- 图形1 -->
                            </colgroup>
                            <tbody ref="scrollContent2">
                                <tr v-for="(item, index) in extendedReason" :key="index">
                                    <td>{{ item.reason }}%</td>
                                    <td>
                                        <div class="bar-wrapper">
                                            <div class="bar" :style="barStyle(item.percentageBar,['#2d79f3','#B634E8'])"></div>
                                        </div>
                                    </td>
                                    <td>{{ item.value }}</td>
                                    <td>{{ item.percentage }}%</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>


    </div>
</template>

<script setup>
import { ref, computed, watch, onMounted,onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { rem2px } from "../../utils/scale"


const chartDom = ref(null)
let myChart=null
const chartOption=ref(null)


//随机数据
const randValue= (number=100) => {
  return Math.round(Math.random() * number)
}
//模拟数据-响应时长
const responseTimeList = ['5分钟', '15分钟', '30分钟', '30分钟以上']
const responseTime = ref([
 {name:'A',value:Array.from({length: 4}, (_, i) =>randValue(2000))},
 {name:'B',value:Array.from({length: 4}, (_, i) =>randValue(2000))},
])

//模拟数据-战败原因
const reason = ref([
  { reason: '其他4S店客户', value: randValue(20000)},
  { reason: '注销或者损失小', value: randValue(20000)},
  { reason: '就近定损(离家远)', value: randValue(20000)},
  { reason: '自己维修修理厂', value: randValue(20000)},
  { reason: '无法联系到客户', value: randValue(20000)},
  { reason: '其他原因', value: randValue(20000)},
  { reason: '原因1', value: randValue(20000)},
  { reason: '原因2', value: randValue(20000)},
  { reason: '原因3', value: randValue(20000)},
  { reason: '原因4', value: randValue(20000)},
]);
//模拟数据-各保司推送线索量占比
const clue=ref([
    { clue: '中国平安', value: randValue(20000)},
    { clue: '保险公司1', value: randValue(20000)},
    { clue: '保险公司2', value: randValue(20000)},
    { clue: '保险公司3', value: randValue(20000)},
    { clue: '保险公司4', value: randValue(20000)},
    // { clue: '保险公司5DD', value: randValue(20000)},
    // { clue: '其他', value: randValue(20000)},

])
/** 计算属性 */
const useReason = computed(() => {
  const sum = reason.value.reduce((acc, current) => acc + current.value, 0);
  const max = Math.max(...reason.value.map(item => item.value)) / sum //求最大的比例作为归一化
  return reason.value.sort((a,b)=>b.value-a.value)//降序
    .map(item => ({
        reason: item.reason,
        value: item.value,
        percentage: ((item.value / sum) * 100 ).toFixed(),
        percentageBar:((item.value / sum) / max * 100 ).toFixed(),//作图的数据
  }));
});

const useClue = computed(() => {
  const sum = clue.value.reduce((acc, current) => acc + current.value, 0);
  const max = Math.max(...clue.value.map(item => item.value)) / sum //求最大的比例作为归一化
  return clue.value.sort((a,b)=>b.value-a.value)//降序
    .map(item => ({
        clue: item.clue,
        percentage: ((item.value / sum) * 100 ).toFixed(),
        percentageBar:((item.value / sum) / max * 100 ).toFixed(),//作图的数据
  }));
});
//生成滚播数据-战败原因
const extendedReason=computed(()=>{
  if (useReason.value.length<=5){
    return [...useReason.value]
  }else{
    return [...useReason.value,...useReason.value]
  }
})
//生成滚播数据-各保司推送线索量占比
const extendedClue=computed(()=>{
  if (useClue.value.length<=5){
    return [...useClue.value]
  }else{
    return [...useClue.value,...useClue.value]
  }
})

const barOption=(xData,series)=>({
    grid:{top:"15%",bottom:"20%",left:"15%"},
    xAxis: {
        type: 'category',
        data:xData,
        axisLabel:{
            fontSize:rem2px(.8),
            interval: 0 // 强制全部显示
        },
        axisTick:{show:false},
    },
    yAxis: {
        type: 'value',
        axisLabel:{
            fontSize:rem2px(.8),
            formatter: function (val) {
                return val; // 直接返回原始值，不加逗号
            }
        },
        splitLine:{show:false},
    },
    label:{
        show:true,
        fontSize:rem2px(.7),
        fontWeight:100,
        color:'#fff',
        position:'outside',
    },
    series
})


const updateBarOption=()=>{
    const colors=[
        {id:0,color1:'#1da7ff',color2:'rgba(29,167,255,0)'},
        {id:1,color1:'#3fc816',color2:'rgba(63,200,22,0)'},
    ]
    const series=responseTime.value.map((item,index)=>({
        type: 'bar',
        barWidth: '20%',
        data:item.value,
        itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color:colors[index].color1 },  // 顶部颜色
            { offset: 1, color: colors[index].color2 }  // 底部透明
            ])
        }
    }))
    chartOption.value = barOption(responseTimeList,series)

    if (chartDom.value) {
        myChart = echarts.init(chartDom.value); 
        myChart.setOption(chartOption.value);
    }
}



const scrollContainer = ref(null);
const scrollContent = ref(null);
const scrollContainer2 = ref(null);
const scrollContent2 = ref(null);


function setupAutoScroll(containerRef, contentRef, speed = 100) {
  let offset = 0;
  setInterval(() => {
    const container = containerRef.value;
    const content = contentRef.value;
    if (!container || !content) return;
    offset++;
    if (offset >= content.scrollHeight / 2) {
      offset = 0;
    }
    container.scrollTop = offset;
  }, speed);
}


onMounted(() => {
  setupAutoScroll(scrollContainer, scrollContent, 100);
  setupAutoScroll(scrollContainer2, scrollContent2, 100);
});

// 初始化图表
onMounted(() => {
  if (chartDom.value) {
    myChart = echarts.init(chartDom.value);
  
    updateBarOption()
    
    const observer = new ResizeObserver(() => {
      myChart?.resize();
    });
    observer.observe(chartDom.value);

    onBeforeUnmount(() => {
      observer.disconnect(); // 停止监听
      myChart?.dispose();
    });
  }

});


// 生成柱状图样式的函数：根据百分比设置宽度和渐变色
const barStyle = (percentage, colors) => ({
  width: percentage + '%',
  background: `linear-gradient(to right, ${colors.join(', ')})`
});
</script>

<style lang="scss" scoped>
@import "../../assets/style/main.scss";
$color-border:#494949;
$color-blue:#1caac8;
$color-green:#3fc816;

.right4{
    
    width: 100%;
    height: 13rem;
    margin-top: 1rem;  
    display: flex;
    justify-content: flex-start;
    position: relative;
}
.section{
    &:nth-of-type(1){//战败原因
        position:absolute;
        margin-left: -11rem;
        width: 22rem;
        height: 100%;
        
    }
    &:nth-of-type(2){//战败原因
        margin-left:11.5rem;
        width: 66rem;
        
    }
    &:nth-of-type(3){//战败原因
        width: 112.6rem;
        margin-left:1rem;
        margin-right: 1.5rem;
    }
}

.chart-box{
    width: 100%;
    height: 11.4rem;
    border-top: 1px solid $color-border;
    border-bottom: 1px solid $color-border;
    background-color: rgba(#00030a,0.6);
    .chart{
        width: 100%;
        height: 100%;
    }
}
.table-box{//table容器
    width: 100%;
    height: 11.4rem;
    border-top: 1px solid $color-border;
    border-bottom: 1px solid $color-border;
    background-color: rgba(#00030a,0.6);
}
.table-wrapper {//整个table容器
  width: 100%;
  height: 98%;
  font-family: sans-serif;
  font-size: 1rem;
  font-weight: 100;
  box-sizing: border-box;
  overflow: hidden;
}

.table-body-scroll {//滚轴
  height: 100%;
  overflow: auto;
  /* 隐藏滚动条 */
  scrollbar-width: none;//Firefox
  -ms-overflow-style: none;//IE 10+ 
  &::-webkit-scrollbar {
    display: none; //Chrome, Safari
  }
}
.unified-table {//table样式
  width: 100%;
  height: 100%;
  border-collapse: collapse;
    th,td {//单元格
        padding: 0 5px;
        text-align: left;
        white-space: nowrap
    }
}
//如果该表格是滚播的，则设置单元格padding为5px，让每一行有点距离
.unified-table.scroll{
    th,td {//单元格
        padding: 5px;
    }
}

.bar-wrapper {//柱形图容器
  height: .6rem;
  border-radius: .2rem;
  overflow: hidden;
  display: flex; 
    .bar {
        height: 100%;
        border-radius:.4rem;
    }
}


</style>